#!/usr/bin/env python3
#encoding=utf8

# 作者	：李治华
# 日期	：2019/6/19
# 文件	：UseDropboxPullLogs.py
# 联系	：lizhihua1009@189.cn

import os
import re
import time

def getDevice():
	# os.system("adb start-server")
	# print("=========== 等待设备连接 ===========")
	output = os.popen("adb devices -l").readlines()
	devices = []
	for index in range(0,len(output)):
		if((re.search("product", output[index]))):
			devices.append(output[index].split("	"))
	# while (len(devices) < 1):
	#	 print("等待设备接入……")
	#	 os.system("adb wait-for-device")
	# print("============ 设备已连接 ============")
	if (len(devices) > 1):
		os.system("adb devices -l")
		serialNum = input("有多个设备连接，请输入要使用设备的序列号（即第一列）：")
	else:
		os.system("adb devices -l")
		serialNum = devices[0][0]
	return serialNum


def getLogs():
	device = getDevice()
	cmdGetRecord = "adb -s {} shell dumpsys dropbox".format(device)
	cmdOutput = "adb -s {} shell dumpsys dropbox --print {} {} {} > {}"
	currenttime = time.strftime("%Y%m%d%H%M%S", time.localtime())
	cmdGetLogcat = "adb -s {} logcat -v time -d > logcat_{}.txt".format(device, currenttime)
	print("导出 Logcat {}_logcat.txt".format(currenttime))
	os.system(cmdGetLogcat)
	dropboxLogs = os.popen(cmdGetRecord).readlines()
	outputfiles = []
	for index in range(0, len(dropboxLogs), 2):
		if (dropboxLogs[index + 1].__contains__("chehejia")):
			temp = dropboxLogs[index - 1].split(" ")
			mDateTime = re.sub(r"\D", "", temp[0] + temp[1])
			mLogType = temp[2]
			mFileName = mDateTime + "_" + mLogType + ".txt"
			outputfiles.append(mFileName)
			print("导出 Log：\t{}".format(mFileName))
			os.system(cmdOutput.format(device, temp[0], temp[1], temp[2], mFileName))
	if (len(outputfiles) == 0):
		for index in range(0, len(dropboxLogs), 2):
			if (dropboxLogs[index].__contains__("anr") | dropboxLogs[index].__contains__("crash")):
				temp = dropboxLogs[index].split(" ")
				mDateTime = re.sub(r"\D", "", temp[0] + temp[1])
				mLogType = temp[2]
				mFileName = mDateTime + "_" + mLogType + ".txt"
				outputfiles.append(mFileName)
				print("导出 Log：\t{}".format(mFileName))
				os.system(cmdOutput.format(device, temp[0], temp[1], temp[2], mFileName))


getLogs()
if __name__ == '__main__':
	pass